// 1.创建一个链表头节点dummy; 创建一个指针curr指向dummy; 创建进位值carry
// 2.同时循环遍历l1,l2
// 3.单位的和sum等于l1该位的值加l2该位的和加carry
// 4.curr的下个节点值为sum取模; carry值为sum除10并向下取整; curr指向下一个节点
// 5.遍历结束后检查carry是否为0,如果为0直接返回链表,如果不为0加入新节点 值为carry

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
// var addTwoNumbers = function (l1, l2) {
//   let dummy = new ListNode(), curr = dummy, carry = 0
//   while (l1 !== null || l2 !== null) {
//     let sum = 0
//     if (l1 !== null) {
//       sum += l1.val
//       l1 = l1.next
//     }
//     if (l2 !== null) {
//       sum += l2.val
//       l2 = l2.next
//     }
//     sum += carry
//     curr.next = new ListNode(sum % 10)
//     carry = Math.floor(sum / 10)
//     curr = curr.next
//   }
//   if (carry > 0) {
//     curr.next = new ListNode(carry)
//   }
//   return dummy.next
// };

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

var addTwoNumbers = function (l1, l2) {
  let head = new ListNode(), p = head, carry = 0
  while (l1 != null || l2 != null) {
    let sum = 0
    if (l1 != null) {
      sum += l1.val
      l1 = l1.next
    }
    if (l2 != null) {
      sum += l2.val
      l2 = l2.next
    }
    sum += carry

    if (sum < 10) {
      p.next = new ListNode(sum)
      carry = 0
    } else {
      p.next = new ListNode(sum - 10)
      carry = 1
    }
    p = p.next
  }

  if (carry == 1) {
    p.next = new ListNode(carry)
  }

  return head.next
};

let a = new ListNode(3), b = new ListNode(4, a), c = new ListNode(2, b)
let a1 = new ListNode(4), b1 = new ListNode(6, a1), c1 = new ListNode(5, b1)
console.log(addTwoNumbers(c, c1))